#!/usr/bin/env python3
"""
详细调试 Discourse 标签搜索问题
"""

import asyncio
import sys
import os
import json

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.services.discourse import DiscourseService
from app.config import settings
from pydiscourse import DiscourseClient

async def debug_discourse_search():
    """详细调试 Discourse 搜索功能"""
    print("=== 详细调试 Discourse 搜索 ===")
    
    print(f"配置信息:")
    print(f"  Base URL: {settings.DISCOURSE_BASE_URL}")
    print(f"  Username: {settings.DISCOURSE_USERNAME}")
    print(f"  API Key: {settings.DISCOURSE_API_KEY[:10]}...")
    
    try:
        # 1. 直接使用 pydiscourse 客户端测试
        print("\n1. 直接测试 pydiscourse 客户端:")
        client = DiscourseClient(
            host=settings.DISCOURSE_BASE_URL,
            api_key=settings.DISCOURSE_API_KEY,
            api_username=settings.DISCOURSE_USERNAME
        )
        
        # 测试基本连接
        try:
            user_info = client.user(settings.DISCOURSE_USERNAME)
            print(f"  连接成功，用户: {user_info.get('username', 'Unknown')}")
        except Exception as e:
            print(f"  连接失败: {e}")
            return
        
        # 测试搜索
        search_queries = ["spring", "#spring"]
        for query in search_queries:
            try:
                print(f"\n  搜索查询: '{query}'")
                results = client.search(query, limit=5)
                posts = results.get('posts', [])
                print(f"    找到 {len(posts)} 个帖子")
                
                if posts:
                    print(f"    第一个帖子 ID: {posts[0].get('id')}")
                    print(f"    第一个帖子用户: {posts[0].get('username')}")
                else:
                    print(f"    没有找到帖子")
                    print(f"    完整搜索结果键: {list(results.keys())}")
                    
            except Exception as e:
                print(f"    搜索 '{query}' 失败: {e}")
        
        # 2. 测试我们的服务类
        print("\n2. 测试 DiscourseService:")
        service = DiscourseService(
            base_url=settings.DISCOURSE_BASE_URL,
            api_key=settings.DISCOURSE_API_KEY,
            username=settings.DISCOURSE_USERNAME
        )
        
        # 测试标签搜索方法
        print(f"  测试 search_posts_by_tags(['spring']):")
        try:
            posts = await service.search_posts_by_tags(['spring'], limit=3)
            print(f"    返回 {len(posts)} 个帖子")
            
            if posts:
                for i, post in enumerate(posts, 1):
                    print(f"    帖子 {i}: ID={post.get('id')}, 用户={post.get('username')}")
            else:
                print(f"    没有返回任何帖子")
                
        except Exception as e:
            print(f"    调用 search_posts_by_tags 失败: {e}")
            import traceback
            traceback.print_exc()
        
        # 3. 手动调用搜索方法内部逻辑
        print("\n3. 手动测试搜索逻辑:")
        try:
            tags = ['spring']
            tag_query = " ".join([f"#{tag}" for tag in tags])
            print(f"  构建的查询: '{tag_query}'")
            
            results = service.client.search(tag_query, limit=20)
            posts = results.get('posts', [])
            print(f"  直接搜索结果: {len(posts)} 个帖子")
            
            if posts:
                print(f"  前3个帖子:")
                for i, post in enumerate(posts[:3], 1):
                    print(f"    {i}. ID={post.get('id')}, 用户={post.get('username')}")
            
        except Exception as e:
            print(f"  手动搜索失败: {e}")
            import traceback
            traceback.print_exc()
    
    except Exception as e:
        print(f"初始化失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_discourse_search())
